from flask import request
from flask.ext.classy import FlaskView,route

from mall.services.additional_item import AdditionalItemService
from ..models.shop_cart import CartItem
from ..schema.error import PARAMS_DOES_NOT_EXIST, success, \
    CART_ITEM_NOT_EXIST, UPDATE_ITEM_ERROR, UPDATA_ITEM_COUNT, CART_ITEM_ERROR
from ..schema.param import shop_cart_item_param
from ..schema.resp import query_schema, CartItemBase, member_not_exist, cart_item_count
from ..services.cart_item import CartItemService
from ..services.currency import CurrencyService
from ..services.member import MemberService
from ..services.offer import OfferService
from ..services.shop_cart import ShopCartService


class ShopCartItemsView(FlaskView):

    @route('/', methods=['POST'])
    def create_shop_cart_item(self):

        data, errors = shop_cart_item_param.load(request.get_json())

        offer_id = data.pop('offer')
        source = data.pop('source')
        member_id = data.pop('member', None)
        count = data.pop('count', 1)
        additives = data.pop('additives', [])

        offer = OfferService.get_offer_by_id(offer_id)
        if not offer:
            pass
            # TODO
        if member_id:
            member = MemberService.get_member_by_id(member_id)
            if not member:
                return member_not_exist.jsonify()
            shop_cart = ShopCartService.get_member_cart(member.id)
            if not shop_cart:
                shop_cart = ShopCartService.create_member_cart(member.id)
        shop_cart_item_list = CartItemService.get_cart_item_by_source(source) or []

        item = None
        # 判断现在报价是否存在
        exist_item = list(filter(lambda i: i.offer_id == offer_id, shop_cart_item_list))
        if exist_item and len(exist_item) > 0:
            # 如果item存在，则只更新count
            item = exist_item[0]
            item.count += count

        else:
            # 不存在，则新创建一个
            item = CartItem(
                offer_id=offer_id,
                product_id=offer.product_id,
                count=count,
                source=source
            )
        # 开始处理 additives
        # 先删除原来存在的additives
        exist_additives = list(item.additives) or []
        # item.additives.remove_all()
        # item.additives.remove()
        for ea in exist_additives:
            item.additives.remove(ea)
        for additive in additives:
            additive_item = AdditionalItemService.get_item_by_id(additive)
            if not additive_item:
                pass
                # TODO 附加项目不存在
            item.additives.append(
                additive_item
                # description = additive_item.screen_name,
            )
        CartItemService.update_item(item)
        return  success.jsonify()
        # if request.data:
        #     try:
        #         data, _ = shop_cart_item_param.load(request.get_json())
        #     except   ValidationError  as  ve:
        #         return PARAMS_ERROR.jsonify(ve)
        #     offer_id = data.pop('offer')
        #     offer = OfferService.get_offer_by_id(offer_id=offer_id)
        #
        #     if not offer:
        #         return STOCK_NOT_EXIST.jsonify()
        #
        #     product_id = offer.product_id
        #     shop_cart = None
        #     if 'member' in data and data['member']:
        #         member_id = data.pop('member')
        #         member = MemberService.get_member_by_id(id=member_id)
        #
        #         if not member:
        #             return MEMBER_NOT_EXIST.jsonify()
        #         else:
        #             shop_cart = ShopCartService.get_shop_cart_id(member_id=member_id)
        #             if not shop_cart:
        #                 shop_cart = ShopCartService.create_member_cart(
        #                     member_id=member_id
        #                     # 'updated_at': datetime.datetime.now(),
        #                     # 'status': 'created',
        #                     # 'created_at': datetime.datetime.now()
        #                 )
        #             count = data.get('count', 1)
        #             source = data.get('source')
        #             product_id = data.get('product_id')
        #             product = ProductService.get_by_id(product_id)
        #             if not product:
        #                 return PRODUCT_NOT_EXIST.jsonify()
        #             cart_item = ShopCartService.get_item_from(source, product_id, offer_id)
        #             if cart_item:
        #                 cart_item.count += count
        #                 cart_item.shop_cart_id = shop_cart.id
        #                 ShopCartService.cart_item_update(count=cart_item.count,shop_cart_id=cart_item.shop_cart_id)
        #             else:
        #                 cart_item = ShopCartService.cart_item_create(
        #                     shop_cart_id=shop_cart.id,
        #                     source=data.pop('source'),
        #                     product_id=product_id,
        #                     offer_id=offer_id,
        #                     count=count
        #                 )
        #             # CartItemAdditive.delete_all_for(cart_item)
        #             # if 'additives' in data:
        #             #     for n in data['additives']:
        #             #         type = n['type']
        #             #         title = ''
        #             #         if type == 'service':
        #             #             service_id = n['service_id']
        #             #             print(service_id)
        #             #             service = ShopCartService.get_service_by_id(service_id=service_id)
        #             #             if not service:
        #             #                 pass
        #             #             else:
        #             #                 title = service.screen_name
        #             #                 ShopCartService.cart_item_additive_create(
        #             #                     type=n['type'],
        #             #                     cart_item=cart_item,
        #             #                     title=title,
        #             #                     required=n.get('required') if 'required' in n else 'N'
        #             #                 )
        #
        #             if cart_item:
        #                 return success.jsonify()
        #             else:
        #                 return PARAMS_DOES_NOT_EXIST.jsonify()
        #     else:return PARAMS_DOES_NOT_EXIST.jsonify()

    #根据source获取购物车信息
    @route('/source/',methods=['GET'])
    def filter_items(self):
        source = request.args.get('source')
        if not source:
            return PARAMS_DOES_NOT_EXIST.jsonify()

        currency = request.args.get('currency')
        if not currency:
            currency = CurrencyService.get_main_currency()
        else:
            currency = CurrencyService.get_currency_by_id(currency)
        cart_items = CartItemService.get_cart_item_by_source(source)
        # if not cart_items:
        #     return CART_ITEM_NOT_EXIST.jsonify()

        shop_cart_items_schema = CartItemBase(many = True, context = {'currency': currency})

        return query_schema.jsonify_with(
            items=shop_cart_items_schema.dump(cart_items).data
        )

    # 根据source获取购物车商品数量
    @route('/source/<source>/count')
    def get_statistics_by_source(self, source):
        count = CartItemService.get_cart_count_by_source(source) or 0
        return cart_item_count.jsonify({'count': count})

    #更新购物车商品删除及数量
    @route('/update/', methods=['POST'])
    def update_cart_items(self):
        data,_ = shop_cart_item_param.load(request.get_json())
        item_id = data.pop('id')
        item = CartItemService.get_item_by_id(id=item_id)
        if not item:
            return CART_ITEM_NOT_EXIST.jsonify()
        else:
            count = data.get('count')
            if count and count > 0:
                cart_item = CartItemService.update_item_count(id=item_id, count=count)
            else:
                return UPDATA_ITEM_COUNT.jsonify()
            if cart_item:
                return success.jsonify()
            else:
                UPDATE_ITEM_ERROR.jsonify()

    #删除购物车中的条目
    @route('/<id>',methods=['POST'])
    def remove_cart_item(self,id):
        item = CartItemService.get_item_by_id(id=id)
        if not item:
            return CART_ITEM_ERROR.jsonify()
        else:
            del_b = CartItemService.delete_item(id=id)
            if del_b:
                return success.jsonify()



